<?php

/**
 * QPHP
 *
 * Copyright (c) 2022 QPHP
 *
 * @author lbnnbs
 * @copyright Copyright (c) 2022 lbnnbs QPHP (https://gitee.com/lbnnbs/qphp)
 * @license AGPLv3 License
 *
 * 用户模型
 */
trait UserModel {

    /**
     * 用户ID字段名
     * @var int
     */
    protected $_uid = 'uid';

    public function updateByUid($uid, $arr) {
        $arr = $this->filter($arr);
        unset($arr[$this->_uid]); // 防范修改uid
        $where = array($this->_uid => $uid);
        return Db()->update(static::$table, $arr, $where);
    }

    public function updateInUid($id, $uid, $arr) {
        $arr = $this->filter($arr);
        unset($arr[$this->_uid]); // 防范修改uid
        $where = array($this->_id => $id, $this->_uid => $uid);
        return Db()->update(static::$table, $arr, $where);
    }

    public function removeByUid($uid) {
        $where = array($this->_uid => $uid);
        return Db()->delete(static::$table, $where);
    }

    public function removeInUid($id, $uid) {
        $where = array($this->_id => $id, $this->_uid => $uid);
        return Db()->delete(static::$table, $where);
    }

    public function getByUid($uid, $field = '') {
        $where = array($this->_uid => $uid);
        if ($field != '') {
            return Db()->getOne(static::$table)->fields($field)->where($where)->result();
        }
        return Db()->getRow(static::$table)->where($where)->result();
    }

    public function getInUid($id, $uid, $field = '') {
        $where = array($this->_id => $id, $this->_uid => $uid);
        if ($field != '') {
            return Db()->getOne(static::$table)->fields($field)->where($where)->result();
        }
        return Db()->getRow(static::$table)->where($where)->result();
    }

    public function getListInUid($uid, $offset = null, $length = null, $filter = array(), $order = '') {
        $order || $order = "{$this->_id} desc";
        $filter[$this->_uid] = $uid;
        return Db()->getAll(static::$table)->where($filter)->order($order)->limit($offset, $length)->result();
    }

    public function countListInUid($uid, $filter = array()) {
        $filter[$this->_uid] = $uid;
        return Db()->count(static::$table)->where($filter)->result();
    }

    public function setSortInUid($id, $uid, $sort) {
        $arr = array($this->_sort => $sort);
        $where = array($this->_id => $id, $this->_uid => $uid);
        return Db()->update(static::$table, $arr, $where);
    }

}
